package drivers

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"

	. "go-share/models"
)

const (
	//APIKEY = "60e4bd1a067d943e147591c1bdbbef62"
	APIKEY      = "6a2734e0f02c4e2685db50731cf29b43"
	SERVICE_URI = "http://www.tuling123.com/openapi/api"
)

const (
	REQUEST_CODE_TEXT = 100000 // 文本类
	REQUEST_CODE_URL  = 200000 // 链接类
	REQUEST_CODE_NEWS = 302000 // 新闻类
	REQUEST_CODE_MENU = 308000 // 菜谱类
)

type QaTulingJson struct {
	Code int           `json:"code"`
	List []interface{} `json:"list"`
	Text string        `json:"text"`
	Url  string        `json:"url"`
}

type QaTuling struct {
}

func NewQaTuling() *QaTuling {
	return &QaTuling{}
}

func (this *QaTuling) SendText(content string, loc string, refId int64, userId int64) (*ReceiveJsonWithQA, error) {

	obj := map[string]interface{}{
		"key":    APIKEY,
		"info":   content,
		"loc":    loc,
		"userid": userId,
	}
	res, _ := json.Marshal(obj)
	body := bytes.NewBuffer([]byte(res))
	data, err := sendRequest(SERVICE_URI, body)
	fmt.Println("data err | ", data)
	if err != nil {
		return nil, err
	}

	var result ReceiveJsonWithQA

	switch data.Code {
	case REQUEST_CODE_TEXT:
		result.Type = LIB_QA_TYPE_TEXT
		result.Text = data.Text

	case REQUEST_CODE_URL:
		result.Type = LIB_QA_TYPE_URL
		result.Text = data.Text
		result.Url = data.Url

	case REQUEST_CODE_NEWS:
		result.Type = LIB_QA_TYPE_NEWS
		result.Text = data.Text
		result.List = data.List

	case REQUEST_CODE_MENU:
		result.Type = LIB_QA_TYPE_MENU
		result.Text = data.Text
		result.List = data.List

	default:
		return nil, errors.New(fmt.Sprintf("%v", data.Text))
	}
	return &result, nil
}

func sendRequest(url string, body io.Reader) (*QaTulingJson, error) {
	response, err := http.Post(url, "application/json;charset=utf-8", body)
	defer response.Body.Close()

	if err != nil {
		return nil, err
	}

	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	var data QaTulingJson
	err = json.Unmarshal(result, &data)

	return &data, err
}
